<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * @todo 	分类
 * @author shiqiliang<ozil1987@gmail.com>
 * @package package_declaration
 * @subpackage mysite
 * @version 2013-11-21
 */
class Categories extends MY_ADMIN_Controller{
	
	private static $cates = array(
		'article' => '文章',
		'product' => '产品',
	);
	
	function __construct() {
		parent::__construct();
		$this->loadModel('Category_model','Category');
	}
	
	/**
	 * 分类列表
	 */
	function index(){
		$this->display('categories/index',array('result'=>$this->loadCategory()));
	}
	
	/**
	 * 添加分类
	 */
	function create(){
		if($this->input->post(null,true)){
			return $this->save('categories/create');
		}else{
			$this->assign['categories'] = $this->loadCategory();
			$this->assign['cates'] = self::$cates;
			$this->display();
		}
	}
	
	/**
	 * 保存分类
	 */
	private function save($type=''){
		$redirect = getRedirect(base_url('admin/categories'));
	
		$this->load->library('form_validation');
		$this->lang->load('template');
	
		if ($this->form_validation->run($type) == FALSE){
			return $this->showMessage(validation_errors());
		}
		$data = $this->input->post(null,true);
		if(($id = $this->Category->save($data['category']))!==false){
			$mes = 'mes_success';
			return $this->showMessage($mes,$redirect);
		}else{
			return $this->showMessage($this->Category->_error);
		}
	}
	
	/**
	 * 编辑分类
	 */
	function edit($id){
		if($this->input->post(null,true)){
			return $this->save('categories/edit');
		}else{
			$res = $this->Category->findByPk($id);
			if(empty($res)){
				return $this->showMessage('error_param',site_url('admin/categories'));
			}
			$this->assign['categories'] = $this->loadCategory();
			$this->assign['category'] = $res[0];
			$this->assign['cates'] = self::$cates;
			$this->display();
		}
	}
	
	/**
	 * 删除分类（只允许删除没有子分类的）
	 */
	function remove($id=null){
		$redirect = getRedirect(base_url('admin/categories'));
		$id = $id>0?$id:intval($this->input->get('id',true));
		$res = $this->Category->findByPk($id);
		if(empty($res)){
			return $this->showMessage('error_param',site_url('admin/categories'));
		}
		$cond = array('where'=>array('parent_id'=>$res[0]['id']));
		$result = $this->Category->find($cond);
		if(!empty($result)){
			return $this->showMessage('error_has_sub',site_url('admin/categories'));
		}
		if($this->Category->removeByPks($id) === true){
			$mes = 'mes_success';
			return $this->showMessage($mes,site_url('admin/categories'));
		}
		return $this->showMessage('failure',site_url('admin/categories'));
	}
	
	private function loadCategory(){
		$type = $this->input->get('type', TRUE);
		$categories = format_tree($this->Category->getCategory($type));
		return $categories;
	}
}
/* End of file categories.php */
/* Location: ./application/controller/admin/categories.php */